import { Component, OnInit,OnDestroy } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { GitAuth, GitConfig } from '@api/git';
import { GitManagerService } from '@common/services/git/gitmanager';
import { AuthDialogComponent } from '../auth-dialog/auth-dialog.component';
import { GitDialogComponent } from '../git-dialog/git-dialog.component';




@Component({
  selector: 'kd-git-manager',
  templateUrl: './git-manager.component.html',
  styleUrls: ['./git-manager.component.scss']
})
export class GitManagerComponent implements OnInit ,OnDestroy{

  displayedColumns: string[] = ['id', 'name', 'url', 'path', 'authid','status'];
  AuthdisplayedColumns : string[] =['id', 'username', 'password'];
  dataSource: GitConfig[];
  authSource :GitAuth[];
  checkcolor = "warn"
  checkList: Set<number>
  authChecklist:Set<number>
  timer :NodeJS.Timer;
  testrowcleck(row: GitConfig) {
    
    if (this.checkList.has(row.id)) {
      this.checkList.delete(row.id)
    } else {
      this.checkList.add(row.id)
    }
    
  }
  authcheck(row:GitAuth){
    if (this.authChecklist.has(row.id)) {
      this.authChecklist.delete(row.id)
    } else {
      this.authChecklist.add(row.id)
    }
    
  }
  GetGitAll() {
    this.git_.getGitConfig().subscribe(
      data => {
        this.dataSource = data
      }
    )
    this.git_.getGitAuth().subscribe(
      data =>{
        this.authSource =data
      }
    )
  }

  DeleteCheck(){
    this.checkList.forEach(id => {
      this.git_.deleteGitconfig(id).subscribe(
        _ => {
        
          this.GetGitAll()
        }
      )
    })
  }
  DeleteCheckAuth(){
    this.authChecklist.forEach(id => {
      this.git_.deleteGitAuth(id).subscribe(
        _ => {
          this.GetGitAll()
        }
      )
    })
  }

  AddNewDialog(){
    const dialogRef =  this.dialog.open(GitDialogComponent)
    dialogRef.afterClosed().subscribe(
      _ => {
        this.GetGitAll()
      }
    )
  }
  AuthDialog(){
    const dialogRef =  this.dialog.open(AuthDialogComponent)
    dialogRef.afterClosed().subscribe(
      _ => {
        this.GetGitAll()
      }
    )
  }
  constructor(
    private readonly git_: GitManagerService,
    public dialog: MatDialog
  ) {
    this.GetGitAll()
    this.checkList = new Set<number>()
    this.authChecklist  = new Set<number>()
  }

  ngOnInit(): void {
    this.timer = setInterval(
      ()=>{this.GetGitAll()},5000
    )
  }

  ngOnDestroy():void{
    //
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }
}
